import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import config from '../config';

export interface UserState {
  token: string;
  username: string;
  uid: number;
}

export const useUserStore = defineStore('user', () => {
  const router = useRouter();
  const token = ref('');
  const username = ref('');
  const uid = ref(0);

  const isAuthenticated = computed(() => !!token.value);

  function setUser(newToken: string, newUsername: string, newUid: number) {
    token.value = newToken;
    username.value = newUsername;
    uid.value = newUid;
    localStorage.setItem(config.storage.token, newToken);
    localStorage.setItem(config.storage.username, newUsername);
    localStorage.setItem(config.storage.uid, String(newUid));
  }

  function clearUser() {
    token.value = '';
    username.value = '';
    uid.value = 0;
    localStorage.removeItem(config.storage.token);
    localStorage.removeItem(config.storage.username);
    localStorage.removeItem(config.storage.uid);
  }

  function logout() {
    clearUser();
    router.push('/login');
  }

  // 初始化时从localStorage恢复用户状态
  const storedToken = localStorage.getItem(config.storage.token);
  const storedUsername = localStorage.getItem(config.storage.username);
  const storedUid = localStorage.getItem(config.storage.uid);
  if (storedToken && storedUsername && storedUid) {
    setUser(storedToken, storedUsername, parseInt(storedUid));
  }

  return {
    token,
    username,
    uid,
    isAuthenticated,
    setUser,
    clearUser,
    logout
  };
}); 